package com.fxu.role.rest;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import com.fxu.framework.biz.rest.ApiBizRest;
import com.fxu.framework.core.base.Result;
import com.fxu.framework.core.service.impl.ApiServiceImpl;
import com.fxu.framework.core.sql.SQuery;
import com.fxu.framework.core.sql.SUtils;
import com.fxu.role.entity.Admin;
import com.fxu.role.entity.AdminRole;
import com.fxu.role.entity.Role;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/***
 * <p>fxu</p>
 * 管理员表：[admin]的业务逻辑接口实现
 * @author fangxu
 * @version 2021-06-03
 ***/
@Component
@RequiredArgsConstructor
public class AdminRestImpl implements ApiBizRest<Admin> {
/*=== 自动生成代码 开始 ===*/
/*=== 自动生成代码 结束 ===*/
	private final ApiServiceImpl apiService;
	@Override
	public Result<Admin> saveBefore(Admin dbBean, Admin bean) {
		if (bean != null) {
			if (bean.getPassword() != null) {
				bean.setPassword(SecureUtil.md5(bean.getPassword()));
			}
		}
		return Result.ok(bean);
	}

	@Override
	public void fillBeans(List<Admin> beans, List<String> showFlags) {
		// 按需要显示数据
		if (showFlags.contains("adminRoleList.role")) {
			Set<Long> roleIds = beans.stream().map(Admin::getAdminRoleList).flatMap(Collection::stream)
					.map(AdminRole::getRoleId).collect(Collectors.toSet());
			List<Role> roleList = apiService.listBy(SUtils.query(Role.class).in(Role::getId, roleIds));
			for (Admin bean : beans) {
				for (AdminRole adminRole : bean.getAdminRoleList()) {
					adminRole.setRole(CollUtil.findOne(roleList, v -> v.getId().equals(adminRole.getRoleId())));
				}
			}
		}
		// showFlags.forEach(System.out::println);
	}
}
